package com.bps.zzant.services;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.util.ResourceUtils;

import com.bps.zzant.model.Email;

public class EmailServiceImpl implements EmailService {
	
	private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
	
	@Autowired
	private JavaMailSenderImpl mailSender;
	
    @Autowired
    private VelocityEngine velocityEngine;
	

	public void sendSimpleMessage(String fromAddress, String toAddress, String subject, String message ){
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", new Boolean("true"));
		
		logger.info(" +++++++in EmailServiceImpl.sendSimpleMessage. From: " + fromAddress  );
		logger.info(" +++++++in EmailServiceImpl.sendSimpleMessage. To: " + toAddress  );
		logger.info(" +++++++in EmailServiceImpl.sendSimpleMessage. Subject: " + subject  );
		logger.info(" +++++++in EmailServiceImpl.sendSimpleMessage. Message: " + message  );
		
		SimpleMailMessage msg = new SimpleMailMessage();
		msg.setFrom(fromAddress);
		msg.setSubject(subject);
        msg.setTo(toAddress);
        msg.setText(message);
        
        try{
        	mailSender.send(msg);
        }
        catch(Exception ex) {
            // simply log it and go on...
            System.err.println(ex.getMessage());            
        }
		
	}
	
    public void emailQuote(final String toEmailAddresses, final String fromEmailAddress, final String subject, final String content, final HttpServletRequest request) {

			MimeMessagePreparator preparator = new MimeMessagePreparator() {
			
				public void prepare(MimeMessage mimeMessage) throws Exception {
				
				 MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
				 message.setTo(toEmailAddresses);
				 message.setFrom(new InternetAddress(fromEmailAddress));
				 message.setReplyTo(new InternetAddress("jzhu@adsales-usa.com"));
				 message.setSubject(subject);
				 
				 Map model = new HashMap();
				 
				 String[] requestURL = request.getRequestURI().split("/");
				 StringBuffer url = new StringBuffer();
				 for(int i=0; i<requestURL.length-1; i++){
					 
					 url.append(requestURL[i]);
				 }
				 
				 
				 String logoUrl = "http://" + request.getServerName()+":"+request.getServerPort()+"/"+url+"/resources/theme/images/big_logo.jpg";
				 logger.info("logoUrl:" + logoUrl);
		         model.put("logo", logoUrl);
		         model.put("contact", "sharon");
		         
				 
		         String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "quotetemplate.vm", "UTF-8", model);
				 
				 message.setText(body, true);
				 
				 //  message.addInline("big_logo", ResourceUtils.getFile(ResourceUtils.getURL("classpath:big_logo.jpg").toURI()));
				 
	/*			 if (!StringUtils.isBlank(attachmentPath)) {
				     FileSystemResource file = new FileSystemResource(attachmentPath);
				     message.addAttachment(attachmentName, file);
				 }*/
				}
			};
			
			this.mailSender.send(preparator);
	}
    
    
    public void sendEmail(final Email email) {

			MimeMessagePreparator preparator = new MimeMessagePreparator() {
			
				public void prepare(MimeMessage mimeMessage) throws Exception {
				
				 MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
				 message.setTo(email.getToEmailAddresses());
				 message.setFrom(email.getFromEmailAddress());
				 message.setReplyTo(new InternetAddress(email.getReplyToEmailAddress()));
				 message.setSubject(email.getSubject());
				 
		         String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, email.getTemplate(), "UTF-8", email.getTemplateMergeModel());
				 
				 message.setText(body, true);
				 
				}
			};
			
			this.mailSender.send(preparator);
	}
    
}
